package com.Policing.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Input.Rfid_Input;
import com.Policing.Okhttps.HttpOkHttp;
import com.Policing.Since_case.Since_case;
import com.Policing.bean.Input_Adapter;
import com.Policing.Adapter.Input_item;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.menu.SlideSideMenuExampleActivity;
import com.demo.WaveSwipeRefreshLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.dialog.LoadingDialog;
import com.hb.dialog.myDialog.MyAlertInputDialog;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zq on 2017/1/13.
 */

public class Fragment2 extends Fragment {
	private ImageView imageView,seek;
	private String url="http://"+ Ip_Set.IP+"/api/assetEntryQuery";
	private String up_url="http://"+ Ip_Set.IP+"/api/assetEntry";
	private SlideSideMenuExampleActivity content;
	private String id;
	private TextView title_text;
	WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
	private List<Input_Adapter> data = new ArrayList<>();
	private List<Input_Adapter> data1 = new ArrayList<>();
	private Handler handler = new Handler();
	private BaseAdapter adapter;
	private ListView listView;
	private String isData="99";
	private LoadingDialog loadingDialog;
	public Fragment2() {
	}
	private void showDialog(){
		getActivity().runOnUiThread(() -> {
			loadingDialog=new LoadingDialog(getContext());
			loadingDialog.setMessage("正在加载中....");
			loadingDialog.show();
		});
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_second2, null);
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		content = (SlideSideMenuExampleActivity) getActivity();
		SharedPreferences mm = getActivity().getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
		id = mm.getString("id","");
        Log.e("数据", id);
		init();
		load();
	}


	private void init() {
		mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) content.findViewById(R.id.main_swipe);
		mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
		mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
		//mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
		mWaveSwipeRefreshLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener(){
			@Override
			public void onRefresh() {
				//模拟3秒的加载过程
				new Handler().postDelayed(() -> {
					load();
					//接下来可以刷新ListView
				}, 1200);


			}

		});
		seek = (ImageView) content.findViewById(R.id.rfid);
		seek.setImageResource(R.mipmap.saixuan);
		seek.setOnClickListener(v -> {
			final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(content).builder()
					.setTitle("请输入种类名称")
					.setEditText("");
			myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (myAlertInputDialog.getResult().equals("")){
						load();
						myAlertInputDialog.dismiss();
					}else {
						List<Input_Adapter> list = new ArrayList<>();
						for (int i =0;i<data.size();i++){
							if (data.get(i).getType().contains(myAlertInputDialog.getResult())){
								list.add(data.get(i));
							}
						}
						data1.clear(); //2020/5/14改清空data后再次搜索的话，就没办法搜索到其他数据了，用data=list然后再去使用data，有点浪费时间
						data1 = list;
						//showMsg(myAlertInputDialog.getResult());
						isData="0";
						Input_item adapter_item = new Input_item(content,R.layout.addrepairs_item,data1);
						listView.setAdapter(adapter_item);
						myAlertInputDialog.dismiss();
					}
				}
			}).setNegativeButton("取消", v1 -> myAlertInputDialog.dismiss());
			myAlertInputDialog.show();
		});
		listView = (ListView) content.findViewById(R.id.listveiw);
		imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
		title_text = (TextView) content.findViewById(R.id.title_text);
		title_text.setText("入库");
		imageView.setOnClickListener(v -> {
			SlideSideMenuTransitionLayout mSlideSideMenu= (SlideSideMenuTransitionLayout)getActivity().findViewById(R.id.slide_side_menu);
			mSlideSideMenu.toggle();
		});

		listView.setOnItemClickListener((parent, view, position, id) -> {
			if(!isData.equals("0")) {
				Log.i("listlist", data.get(position).getType());
				Intent intent = new Intent(content, Rfid_Input.class);
				intent.putExtra("assetId", data.get(position).getAssetId());
				intent.putExtra("assetNumber", data.get(position).getAssetNumber());
				intent.putExtra("istag", data.get(position).getIstag());
				startActivity(intent);
			}
			else {
				isData="99";
				Intent intent = new Intent(content, Rfid_Input.class);
				intent.putExtra("assetId", data1.get(position).getAssetId());
				intent.putExtra("assetNumber", data1.get(position).getAssetNumber());
				intent.putExtra("istag", data1.get(position).getIstag());
				startActivity(intent);
			}
		});

	}
	private void load() {
		showDialog();
	new Thread(() -> {
	try {
		Map<String,String> map = new HashMap<>();
		map.put("id",id);
map.put("source", Since_case.set().getSource());
		Log.e("数据数据数据", "id"+id+"source"+Since_case.set().getSource()+"--"+url );
		HttpOkHttp.getInstance().requestPost(url, map, new HttpOkHttp.OkHttpCallBack<String>() {
			@Override
			public void requestSuccess(String s) {
				data.clear();
				Bitmap bitmap =null;
				Gson gson = new Gson();
				List<Input_Adapter> userList = gson.fromJson(s, new TypeToken<List<Input_Adapter>>(){}.getType());
				for(int i = 0;i < userList.size();i++){
					String s1 ="";
					String type = userList.get(i).getType();
					String factory = userList.get(i).getFactory();
					String assetId =userList.get(i).getAssetId();
					String istag= userList.get(i).getIstag();
					String model = userList.get(i).getModel();
					String assetNumber = userList.get(i).getAssetNumber();
					if (istag.equals("1")){
						s1 = "是";
					}else if (istag.equals("0")){
						s1 = "否";
					}
					if(!userList.get(i).getImage().equals("")){
byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
}
					/*if (userList.get(i).getImage().equals("")){
						if (isAdded()) {
							@SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
							bitmap = BitmapFactory.decodeStream(is);
						}
					}*/
					data.add(new Input_Adapter(bitmap,"种类名称",type,"规格型号",model,"生产厂家",factory,"是否带标",s1,assetId,assetNumber));
				}
				content.runOnUiThread(() -> {
					mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
					Input_item adapter_item = new Input_item(content,R.layout.addrepairs_item,data);
					listView.setAdapter(adapter_item);
					loadingDialog.cancel();
				});
			}

			@Override
			public void requestFailure(String message) {
				content.runOnUiThread(() -> {
					Toast.makeText(content,"服务器error！！",Toast.LENGTH_SHORT).show();
					loadingDialog.cancel();
				});
				Log.i("datadata",message);
			}
		},String.class);
	}catch (Exception e){
		content.runOnUiThread(() -> {
			Toast.makeText(content,"error！！",Toast.LENGTH_SHORT).show();
			loadingDialog.cancel();
		});
	}

	}).start();

	}

	@Override
	public void onStart() {
		/*Timer timer=new Timer();//实例化Timer类
		timer.schedule(new TimerTask(){
			public void run(){
				load();
				this.cancel();
			}
		},200);//五百毫秒*/
		super.onStart();
	}

}
